<template>
  <div>
    <el-collapse v-model="activeNames">
      <el-collapse-item name="1">
        <template slot="title"> 自定义规格项 </template>
        <div class="box-wrapper">
          <div class="box" v-for="(item, index) in specList" :key="item.specId">
            <div class="delete-spec" v-if="!forbid">
              <el-button type="danger" size="small" @click.native="handleDelSpecItem(index)">删除规格</el-button>
            </div>
            <el-row class="header-spec">
              <div class="item">
                <div class="label">规格名</div>
                <div class="value">
                  <el-select
                    :disabled="forbid"
                    class="readonly"
                    size="small"
                    v-model.trim="item.specName"
                    placeholder="可选择或输入规格名"
                    clearable
                    filterable
                    allow-create
                    default-first-option
                    @change="specNameChange(item, $event)"
                  >
                    <el-option v-for="(item, index) in selectedList" :value="item.value" :label="item.label" :key="index"> </el-option>
                  </el-select>
                </div>
              </div>
              <div class="item">
                <div class="label">规格单位</div>
                <div class="value">
                  <el-input :readonly="forbid" v-model="item.specUnit" size="small"></el-input>
                </div>
              </div>
              <div class="item">
                <div class="label">规格描述</div>
                <div class="value">
                  <el-input :readonly="forbid" v-model="item.specDesc" size="small"></el-input>
                </div>
              </div>
            </el-row>
            <el-row>
              <div class="item" v-for="(item2, index2) in item.specValList">
                <div class="label">规格值</div>
                <div class="value">
                  <el-input :readonly="forbid" v-model.trim="item2.specVal" size="small" @blur="handleBlurSpecVal(item2, index2, item.specValList)"></el-input>
                </div>
                <div>
                  <el-button size="mini" type="danger" v-if="!forbid" @click="handleDelSpecVal(item.specValList, index2)">删除</el-button>
                </div>
              </div>
            </el-row>
            <div class="bottom" v-if="!forbid">
              <el-button @click.native="handleAddSpecVal(item)" size="small">添加规格值</el-button>
            </div>
          </div>
        </div>
        <div class="operate" v-if="!forbid">
          <el-button type="danger" size="mini" @click="handleAddSpecItem">添加规格项</el-button>
          <el-button type="warning" size="mini" @click="handleClearSpecItem">清空规格项</el-button>
        </div>
      </el-collapse-item>
      <el-collapse-item name="2">
        <template slot="title"> 规格详情 </template>
        <el-table :data="tableList" :header-cell-style="{ 'background-color': '#F7F7F7' }" style="padding: 0 !important">
          <el-table-column align="center" width="140" v-for="(item, index) in specList" :label="item.specName || '#'" :key="index" fixed>
            <template slot-scope="scope">
              {{ scope.row.variantSpecs[index].specVal }}
            </template>
          </el-table-column>
          <el-table-column label="时长值" align="center" width="240" v-if="serverType == 3">
            <template slot-scope="scope">
              <el-input v-model="scope.row.rentTime" type="number" @input="handleMoneyInputList(scope.row, 5)">
                <el-select class="select" style="width: 80px" v-model="scope.row.rentUnit" slot="append" placeholder="选择">
                  <el-option v-for="item in timeUnit" :label="item.label" :value="item.value" :key="item.value"></el-option>
                </el-select>
              </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                时长值
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy(['rentTime', 'rentUnit'])" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="是否计时" align="center" v-if="serverType == 3" width="140">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.rentFlag" :active-value="1" :inactive-value="0"> </el-switch>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                是否计时
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('rentFlag')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="续费时长" width="240" v-if="serverType == 3">
            <template slot-scope="scope">
              <el-input v-show="!scope.row.rentFlag" type="number" v-model="scope.row.renewTime" @input="handleMoneyInputList(scope.row, 10)">
                <el-select class="select" style="width: 94px" v-model="scope.row.renewUnit" slot="append" placeholder="选择">
                  <el-option v-for="item in timeUnit" :label="item.label" :value="item.value" :key="item.value"></el-option>
                </el-select>
              </el-input>
              <span v-show="scope.row.rentFlag">#</span>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                续费时长
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy(['renewTime', 'renewUnit'])" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="续费价格(元)" width="140" v-if="serverType == 3">
            <template slot-scope="scope">
              <el-input v-show="!scope.row.rentFlag" type="number" v-model="scope.row.renewPrice" @input="handleMoneyInputList(scope.row, 7)"> </el-input>
              <span v-show="scope.row.rentFlag">#</span>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                续费价格
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('renewPrice')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="起步价(元)" width="140" v-if="serverType == 3">
            <template slot-scope="scope">
              <el-input v-show="scope.row.rentFlag" type="number" v-model.number="scope.row.startFee" @input="handleMoneyInputList(scope.row, 8)"> </el-input>
              <span v-show="!scope.row.rentFlag">#</span>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                起步价(元)
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('startFee')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="押金(元)" width="140" v-if="serverType == 3">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.deposit" @input="handleMoneyInputList(scope.row, 6)"> </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                押金(元)
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('deposit')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>

          <template v-if="serverType == 4">
            <el-table-column width="300" align="center">
              <template slot-scope="{ row }">
                <el-select v-model="row.waiters" value-key="id" multiple>
                  <el-option v-for="item in waiterList" :value="item" :label="item.name" :key="item.id"></el-option>
                </el-select>
              </template>
              <template slot="header" slot-scope="scope">
                <div>
                  服务员
                  <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                    <el-button class="copy" slot="reference" @click="handleCopy('waiters')" type="danger" size="mini">复制</el-button>
                  </el-popover>
                </div>
              </template>
            </el-table-column>
            <el-table-column width="120" align="center" label="服务员工作时间">
              <template slot-scope="{ row, $index }">
                <el-button size="mini" type="success" plain @click="checkWaiterTime(row, $index)">编辑工作时间</el-button>
              </template>
            </el-table-column>
          </template>

          <el-table-column align="center" width="190">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.price" @input="handleMoneyInputList(scope.row, 0)"> </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                平台原价(元)
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('price')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="salePrice" label="售价(元)" width="190">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.salePrice" @input="handleMoneyInputList(scope.row, 1)"> </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                平台售价(元)
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('salePrice')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="marketPrice" label="商户原价(元)" width="190">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.marketPrice" @input="handleMoneyInputList(scope.row, 9)" @blur="handleMarketPriceBlur(scope.row)"> </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                商户原价(元)
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('marketPrice')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="discount" align="center" prop="discount" label="商户折扣比例" width="190">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.discount" @input="handleMoneyInputList(scope.row, 4)" @blur="handleDiscountBlur(scope.row)">
                <span slot="suffix" style="line-height: 32px">%</span>
              </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                商户折扣比例
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('discount')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="costPrice" label="成本价(元)" width="190">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.costPrice" @input="handleMoneyInputList(scope.row, 2)" @blur="handleCostBlur(scope.row)"> </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                成本价(元)
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('costPrice')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="packageFee" label="包装费(元)" width="190">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.packageFee" @input="handleMoneyInputList(scope.row, 3)"> </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                包装费(元)
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('packageFee')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="packageDiscount" label="包装费折扣比例" width="190">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.packageDiscount" @input="handleMoneyInputList(scope.row, 11)">
                <span slot="suffix" style="line-height: 32px">%</span>
              </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                包装费折扣比例
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('packageDiscount')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" v-if="showStock" width="120">
            <template slot-scope="scope">
              <el-input :readonly="forbid" v-model="scope.row.stock" @input="handleStockInput(scope.row)"></el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                库存
                <el-popover v-if="tableList.length > 1 && !forbid && showStock" placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('stock')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="主图" width="170">
            <template slot-scope="scope">
              <upload-img :index="scope.$index" class="upload-img" @uploadFileList="getFileUrl" :folder="folder">
                <img width="100%" v-if="scope.row.mainImg" :src="scope.row.mainImg" alt="" />
                <i v-if="!scope.row.mainImg" class="el-icon-plus"></i>
              </upload-img>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                主图
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('mainImg')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="图片" width="250">
            <template slot-scope="scope">
              <div class="more-img__container">
                <div class="more-img" v-for="(item, index) in scope.row.moreImg" :key="index">
                  <el-image :src="item" :preview-src-list="scope.row.moreImg"> </el-image>
                  <span class="el-icon-close" @click="scope.row.moreImg.splice(index, 1)"></span>
                </div>
                <upload-img
                  v-show="scope.row.moreImg.length != 5"
                  :index="scope.$index"
                  :param="{ moreImg: true }"
                  :limit="5 - scope.row.moreImg.length"
                  class="upload-img more-img__upload"
                  @uploadFileList="getFileUrl"
                  :folder="folder"
                >
                  <i class="el-icon-plus"></i>
                </upload-img>
              </div>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                更多图片
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('moreImg')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>

          <el-table-column v-if="saleState" align="center" label="状态" width="100">
            <template slot-scope="scope">
              <el-select size="small" v-model="scope.row.saleState">
                <el-option v-for="item in $Options.saleStateList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
              </el-select>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                状态
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('saleState')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="简介" class="introduce" :width="introduceWidth">
            <template slot-scope="scope">
              <el-input type="textarea" v-model="scope.row.introduce"></el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>
                简介
                <el-popover placement="top-start" width="200" trigger="hover" content="复制该列第一行的值至所有行。">
                  <el-button class="copy" slot="reference" @click="handleCopy('introduce')" type="danger" size="mini">复制</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="默认" :width="defaultWidth">
            <template slot-scope="scope">
              <el-button class="def-btn" size="mini" plain v-show="scope.row.defaultFlag" type="danger">默认值</el-button>
              <el-button class="def-btn" size="mini" plain @click="handleSetDefault(scope.row)" v-show="!scope.row.defaultFlag" type="info">设为默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
      <el-collapse-item name="3">
        <template slot="title"> 折扣金 </template>
        <div style="width: 100%; padding: 20px 0; text-align: center" v-if="info.relationAmountType.length === 0">请先绑定折扣金</div>
        <el-table v-if="info.relationAmountType.length > 0 && !hasSku" :data="tableList" :header-cell-style="{ 'background-color': '#F7F7F7' }" style="padding: 0 !important">
          <el-table-column align="center" width="140" v-for="(item, index) in specList" :label="item.specName || '#'" :key="index" fixed>
            <template slot-scope="scope">
              {{ scope.row.variantSpecs[index].specVal }}
            </template>
          </el-table-column>
          <el-table-column align="center" width="190" v-if="info.relationAmountType.find((i) => i === 1)">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.discountOld"  @input="inputVerify(1,scope.row)"/>
            </template>
            <template slot="header" slot-scope="scope">
              <div>养老金最高抵扣(元)</div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="190" v-if="info.relationAmountType.find((i) => i === 1)">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.rebateOld"  @input="inputVerify(2,scope.row)"/>
            </template>
            <template slot="header" slot-scope="scope">
              <div>养老金返利额(元)</div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="190" v-if="info.relationAmountType.find((i) => i === 2)">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.discountPmc"  @input="inputVerify(3,scope.row)"/>
            </template>
            <template slot="header" slot-scope="scope">
              <div>物业金最高抵扣(元)</div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="190" v-if="info.relationAmountType.find((i) => i === 2)">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.rebatePmc" @input="inputVerify(4,scope.row)"> </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>物业金返利额(元)</div>
            </template>
          </el-table-column>
        </el-table>
        <el-table v-if="info.relationAmountType.length > 0 && hasSku" :data="subsidyAmountTableList" :header-cell-style="{ 'background-color': '#F7F7F7' }" style="padding: 0 !important">
          <el-table-column align="center" width="190" v-if="info.relationAmountType.find((i) => i === 1)">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.discountOld"  @input="inputVerify(1,scope.row)"/>
            </template>
            <template slot="header" slot-scope="scope">
              <div>养老金最高抵扣(元)</div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="190" v-if="info.relationAmountType.find((i) => i === 1)">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.rebateOld"  @input="inputVerify(2,scope.row)"/>
            </template>
            <template slot="header" slot-scope="scope">
              <div>养老金返利额(元)</div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="190" v-if="info.relationAmountType.find((i) => i === 2)">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.discountPmc"  @input="inputVerify(3,scope.row)"/>
            </template>
            <template slot="header" slot-scope="scope">
              <div>物业金最高抵扣(元)</div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="190" v-if="info.relationAmountType.find((i) => i === 2)">
            <template slot-scope="scope">
              <el-input type="number" v-model.number="scope.row.rebatePmc" @input="inputVerify(4,scope.row)"> </el-input>
            </template>
            <template slot="header" slot-scope="scope">
              <div>物业金返利额(元)</div>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>
    <el-dialog :visible.sync="showWaiterTime.show" title="服务员工作时间" center width="fit-content">
      <WaiterTime :waiters="showWaiterTime.waiters" :relationWaiters="showWaiterTime.relationWaiters"></WaiterTime>
      <!-- <div slot="footer">
          <el-button @click="confirmRelationWaiters" type="primary">确 定</el-button>
          <el-button @click="showWaiterTime.show = false">取 消</el-button>
        </div> -->
    </el-dialog>
  </div>
</template>

<script>
import UploadImg from './UploadImg.vue';
import WaiterTime from './WaiterTime.vue';
import SpecApi from '@/api/goods/spec';
import Sortable from 'sortablejs';
import WaiterApi from '@/api/business/waiter';
import { ESubsidyAmount } from '@/enum';
export default {
  props: {
    folder: {
      type: String,
      required: true,
    },
    info: {
      type: Object,
    },
    specList: {
      type: Array,
    },
    subsidyAmountTableList: {
      type: Array,
    },
    tableList: {
      type: Array,
    },
    saleState: {
      type: Boolean,
      default: false,
    },
    mainImg: {
      type: String,
      default: '',
    },
    showStock: {
      type: Boolean,
      default: true,
    },
    forbid: {
      type: Boolean,
      default: false,
    },
    sort: {
      type: Boolean,
      default: true,
    },
    serverType: {
      type: Number | String,
      // default:
    },
  },
  data() {
    return {
      activeNames: ['1', '2', '3'],
      selectedList: [],
      timeUnit: [
        { value: 1, label: '分钟' },
        { value: 2, label: '小时' },
        { value: 3, label: '天' },
      ],
      waiterList: [],
      showWaiterTime: {
        show: false,
        waiters: [],
        relationWaiters: [],
      },
      rowItem: {}, // 当前处理哪一行项
      rowIndex: '', // 当前处理哪一行索引
      verifyDiscount: 0,
      subsidyAmountList: ESubsidyAmount,
      hasSku: false,
    };
  },
  computed: {
    discount() {
      return this.info.hasOwnProperty('discount');
    },
    introduceWidth() {
      const { tableList, showStock, info } = this;
      if (
        !showStock &&
        tableList.length &&
        tableList[0].variantSpecs.length == 1 &&
        this.serverType != 3
        // info.goodsType != 3 &&
        // info.serverType != 3
      ) {
        return '';
      } else {
        return '200';
      }
    },
    defaultWidth() {
      const { tableList, showStock, info } = this;
      if (
        !showStock &&
        tableList.length &&
        tableList[0].variantSpecs.length == 1 &&
        this.serverType != 3
        // info.goodsType != 3 &&
        // info.serverType != 3
      ) {
        return '';
      } else {
        return '180';
      }
    },
  },
  watch: {
    specList: {
      handler(newVal, oldVal) {
        this.hasSku = newVal.length === 0;
        // 这里需要判断，如果新的数据等于旧的数据那么就不是父传子，不是父传子就需要重新获取表格数据
        if (newVal != oldVal) {
          // this.getSpecTable()
          // } else {
          if (newVal && newVal.length) {
            let arr = [];
            newVal.forEach((item, index) => {
              // console.log(arr[index],"arr[index]")
              arr[index] = item.specValList.map((item) => item.specVal);
            });
            arr = this.calculateCombine(arr);
            // console.log(arr,"得到从父组件传过来的规格组合之后的arr")
            //得到规格组合之后的arr
            const tableList = [];
            arr.forEach((item) => {
              const val = this.tableList.find((item2) => item.join(':') == item2.sku);
              if (val.relationWaiters) {
                // 存在服务员需要添加
                const waiters = val.relationWaiters.map((item2) => ({
                  id: item2.waiterId,
                  name: item2.waiterName,
                }));
                this.$set(val, 'waiters', waiters);
              }
              tableList.push(val);
            });
            this.tableList.length = 0;
            this.tableList.push.apply(this.tableList, tableList);
            this.proxyData();
          }
          // 是父传子需要把specName与sku进行代理
        }
      },
      // deep: true,
    },
    'info.businessId': {
      handler(newValue, oldValue) {
        if (newValue) {
          // 当 businessId 属性发生变化时执行操作
          this.getCheckoutInfo(newValue);
          // 执行其他操作...
        }
      },
      immediate: true, // 立即执行一次
    },
    'info.relationAmountType': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.tableList.forEach((item, index) => {
            if (!newValue.includes(1)) {
              this.$set(this.tableList, index, { ...item, discountOld: '', rebateOld: '' });
            }
            if (!newValue.includes(2)) {
              this.$set(this.tableList, index, { ...item, discountPmc: '', rebatePmc: '' });
            }
          });
          this.subsidyAmountTableList.forEach((item, index) => {
            if (!newValue.includes(1)) {
              this.$set(this.subsidyAmountTableList, index, { ...item, discountOld: '', rebateOld: '' });
            }
            if (!newValue.includes(2)) {
              this.$set(this.subsidyAmountTableList, index, { ...item, discountPmc: '', rebatePmc: '' });
            }
          });
        }
      },
      immediate: true,
    },
  },
  components: {
    UploadImg,
    WaiterTime,
  },
  mounted() {
    this.hasSku = this.tableList.length === 0;
    this.getWaiterList();
    SpecApi.listIdName().then((res) => {
      res.data.forEach((item) => {
        item.value = item.specName;
        item.label = item.specName;
      });
      this.selectedList = res.data;
      // 排序

      if (this.sort) {
        this.initSort();
      }
    });
    // this.getCheckoutInfo()
  },
  methods: {
    getCheckoutInfo(businessId) {
      SpecApi.getCheckoutInfo({ businessId }).then((res) => {
        if (res.status == 0) {
          this.verifyDiscount = res.data.discount;
        }
      });
    },
    async getWaiterList() {
      const { data } = await WaiterApi.listIdName({ jobType: 1 });
      this.waiterList = data || [];
    },
    initSort() {
      const el = document.querySelector('.box-wrapper');
      new Sortable(el, {
        onEnd: (e) => {
          // 监听拖动结束事件
          // 这里就可以写我们需要传给后台的逻辑代码
          // 我们有了 e.oldIndex 和 e.newIndex 这两个参数做索引，我们可以根据绑定在表格上面的 data 这个 Array 找到两个相应的记录。就可以针对数据进行操作啦。
          // 下面将拖拽后的顺序进行修改
          const { specList, tableList } = this;
          const currRow = specList.splice(e.oldIndex, 1)[0];
          specList.splice(e.newIndex, 0, currRow);
          specList.forEach((item, index) => {
            item.sort = index + 1;
          });
          // 排序结束后直接重置表格
          this.getSpecTable(true);
        },
      });
    },
    handleGetTable() {
      this.getSpecTable();
    },
    // 添加规格值
    handleAddSpecVal(specList) {
      let specValList = specList.specValList;
      if (specValList.length > 0 && specValList.some((item) => !item.specVal)) {
        this.$message.error('请先填写规格值');
        return;
      }
      specValList.push({ specVal: '' });
    },
    // 删除规格值
    handleDelSpecVal(specValList, index) {
      if (specValList.length <= 1) {
        this.$message.error('至少保留一个规格值');
        return;
      }
      specValList.splice(index, 1);
      this.handleGetTable();
    },
    // 规格值失焦
    handleBlurSpecVal(obj, i, list) {
      const res = list.find((item, index) => item.specVal == obj.specVal && index != i);
      if (res) {
        this.$message.error('规格值' + res.specVal + '重复');
        obj.specVal = '';
        return;
      }
      this.handleGetTable();
    },
    specNameChange(val, specName) {
      const { selectedList } = this;
      let arr = [];
      if (!specName) return;
      const temp = selectedList.find((item) => item.specName == specName);
      if (temp) {
        val.specDesc = temp.specDesc || '';
        val.specUnit = temp.specUnit || '';
        arr = temp.strSpecVal.split(',').map((item) => ({ specVal: item }));

        if (val.specValList.length == arr.length) {
          arr.forEach((item, index) => {
            val.specValList[index].specVal = item.specVal;
          });
        } else {
          val.specValList = arr;
        }
      }
      this.handleGetTable();
    },
    // 库存输入
    handleStockInput(row) {
      row.stock = row.stock.replace(/[^0-9]|^0/g, '');
    },
    // 删除规格项
    handleDelSpecItem(index) {
      this.specList.splice(index, 1);
      this.handleGetTable();
    },
    // 添加规格项
    handleAddSpecItem() {
      if (this.specList.length > 0 && this.specList.some((item) => !item.specName)) {
        this.$message.error('请先填写规格项');
        return;
      }
      let temp = {
        specName: '',
        specType: 1,
        specUnit: '',
        specDesc: '',
        test: 1,
        specValList: [{ specVal: '' }],
        sort: this.specList.length + 1,
      };
      this.specList.push(temp);

      this.handleGetTable();
    },
    // 清空规格项
    handleClearSpecItem() {
      const length = this.specList.length;
      const lenght2 = this.tableList.length;
      for (let i = 0; i < length; i++) {
        this.specList.pop();
      }
      for (let i = 0; i < lenght2; i++) {
        this.tableList.pop();
      }
      /**
       * 这里直接赋值未0要执行下面的$forceUpdate，且只会让该组件更新，不会让父组件更新，当然，可以是使用双向绑定
       */
      // this.specList.length = 0;
      // this.tableList.length = 0;
      // this.$forceUpdate();
      this.handleGetTable();
    },
    // 商户原价改变
    handleMarketPriceBlur(row) {
      const { marketPrice, discount, costPrice } = row;
      if (costPrice && marketPrice && costPrice > marketPrice) {
        row.marketPrice = '';
        row.discount = '';
        this.$message.error('商户原价不能小于成本价');
        return;
      }

      row.costPrice = parseFloat(((marketPrice * discount) / 100).toFixed(4));
    },
    // 商户折扣比例改变
    handleDiscountBlur(row) {
      const { marketPrice, discount } = row;
      row.costPrice = parseFloat(((marketPrice * discount) / 100).toFixed(4));
    },
    handleCostBlur(row) {
      const { costPrice, marketPrice } = row;
      if (costPrice == 0) {
        return;
      }
      if (costPrice && marketPrice && costPrice > marketPrice) {
        row.marketPrice = '';
        row.discount = '';
        this.$message.error('成本价不能大于商户原价');
        return;
      }
      row.discount = parseFloat(((costPrice / marketPrice) * 100).toFixed(2));
    },
    handleMoneyInputList(row, flag) {
      // flag为0表示原价，为1表示配送费，为2表示包装费,3表示商户折扣比例
      if (!flag) {
        // 只保留两位小数
        row.price = parseFloat(parseFloat(row.price).toFixed(2));
        !row.price ? (row.price = 0) : '';
      } else if (flag == 1) {
        row.salePrice = parseFloat(parseFloat(row.salePrice).toFixed(2));
        !row.salePrice ? (row.salePrice = 0) : '';
      } else if (flag == 2) {
        row.costPrice = parseFloat(parseFloat(row.costPrice).toFixed(2));
        !row.costPrice ? (row.costPrice = 0) : '';
      } else if (flag == 3) {
        row.packageFee = parseFloat(parseFloat(row.packageFee).toFixed(4));
        !row.packageFee ? (row.packageFee = 0) : '';
      } else if (flag == 4) {
        row.discount = parseFloat(parseFloat(row.discount).toFixed(2));
        if ((row.discount && row.discount > this.verifyDiscount) || row.discount < 0) {
          row.discount = '';
          this.$message.error(`商户折扣比例只能是0-${this.verifyDiscount}之间`);
        } else if (row.discount || row.discount === 0) {
          row.discount = parseFloat(parseFloat(row.discount).toFixed(2));
        } else {
          row.discount = '';
        }
      } else if (flag == 5) {
        row.rentTime = parseFloat(parseFloat(row.rentTime).toFixed(2));
        !row.rentTime ? (row.rentTime = '') : '';
      } else if (flag == 6) {
        row.deposit = parseFloat(parseFloat(row.deposit).toFixed(2));
        !row.deposit ? (row.deposit = '') : '';
      } else if (flag == 7) {
        row.renewPrice = parseFloat(parseFloat(row.renewPrice).toFixed(2));
        !row.renewPrice ? (row.renewPrice = '') : '';
      } else if (flag == 8) {
        row.startFee = parseFloat(parseFloat(row.startFee).toFixed(2));
        !row.startFee ? (row.startFee = 0) : '';
      } else if (flag == 9) {
        row.marketPrice = parseFloat(parseFloat(row.marketPrice).toFixed(2));
        !row.marketPrice ? (row.marketPrice = 0) : '';
      } else if (flag == 10) {
        row.renewTime = parseFloat(parseFloat(row.renewTime).toFixed(2));
        !row.renewTime ? (row.renewTime = '') : '';
      } else if (flag == 11) {
        row.packageDiscount = parseFloat(parseFloat(row.packageDiscount).toFixed(2));
        if ((row.packageDiscount && row.packageDiscount > this.verifyDiscount) || row.packageDiscount < 0) {
          row.packageDiscount = '';
          this.$message.error(`包装费折扣比例只能是0-${this.verifyDiscount}之间`);
        } else if (row.packageDiscount || row.packageDiscount === 0) {
          row.packageDiscount = parseFloat(parseFloat(row.packageDiscount).toFixed(2));
        } else {
          row.packageDiscount = '';
        }
      }
    },
    // 复制第一行的库存到下面的所有库存呢
    handleCopy(prop) {
      if (Array.isArray(prop)) {
        prop.forEach((item) => {
          this.tableList.forEach((item2) => {
            item2[item] = this.tableList[0][item];
            if (prop === 'waiters') {
              item2.relationWaiters = JSON.parse(JSON.stringify(this.tableList[0].relationWaiters));
            }
            if (prop === 'moreImg') {
              item2.moreImg = JSON.parse(JSON.stringify(this.tableList[0].moreImg));
            }
          });
        });
      } else {
        this.tableList.forEach((item) => {
          item[prop] = this.tableList[0][prop];
          if (prop === 'waiters') {
            item.relationWaiters = JSON.parse(JSON.stringify(this.tableList[0].relationWaiters));
          }
          if (prop === 'moreImg') {
            item.moreImg = JSON.parse(JSON.stringify(this.tableList[0].moreImg));
          }
        });
      }
    },
    // 获取图片
    getFileUrl(val) {
      if (val) this.$Utils.notifySuccess('上传成功');
      const { index, param, uploadFileList } = val;
      if (param && param.moreImg) {
        this.tableList[index].moreImg.push(uploadFileList[0]);
      } else {
        this.tableList[index].mainImg = uploadFileList[0];
      }
    },

    /**
     * @处理所有的规格
     * @param {boolean} flag 如果flag为true表示一定重置表格
     */

    getSpecTable(flag = false) {
      // 判断表格需不需要重置,只是改变了数据并没有删除的话就不需要把表格数修改
      let list = this.specList; //这里是规格数据列表
      let specList = list.map((item) => {
        return [...item.specValList.filter((item) => item.specVal)];
        //这里返回的是规格值列表的数组
      });
      // 计算生成表格
      specList = this.calculateCombine(specList);
      // calculateCombine这个方法的用途是组合每个规格项和规格值
      // console.log(specList,"这是计算生成的规格项和值的组合")
      this.judgeShowSave(specList);

      if (!this.judgeResetTable(flag)) return;
      console.log('重置表格');

      let temp = [];
      let info = this.info;
      specList.forEach((item) => {
        let obj = {
          variantId: '',
          mainImg: this.mainImg ? this.mainImg : '',
          moreImg: [],
          relationWaiters: [],
          waiters: [],
          price: info.price,
          renewTime: '',
          renewUnit: 1,
          renewPrice: '',
          introduce: '',
          salePrice: info.salePrice,
          stock: 999999,
          costPrice: info.costPrice,
          packageFee: info.packageFee,
          packageDiscount: info.packageDiscount || '',
          marketPrice: info.marketPrice,
          rentTime: '',
          rentFlag: 0,
          rentUnit: 1,
          deposit: info.deposit || '',
          startFee: '',
          variantState: 1,
          defaultFlag: 0,
          variantSpecs: JSON.parse(JSON.stringify(item)),
          discountOld: '',
          rebateOld: '',
          rebatePmc: '',
          discountPmc: '',
        };
        this.discount ? (obj.discount = info.discount) : '';
        this.saleState ? (obj.saleState = 2) : '';
        temp.push(obj);
      });
      //需要和原来的规格列表做比较，如果存在一样把原来的一行搬过去
      this.compareSpec(temp, this.tableList);
      // 这里要做数据代理，因为如果不重新获取表格的话就需要把自定义规格中的一些信息代理规格表格中的一些信息
      this.proxyData();
    },
    // 对表格中的数据，specName与sku和specVal进行数据代理
    proxyData() {
      let _this = this;
      let specList = this.specList.map((item) => {
        return item.specValList.filter((item) => item.specVal);
      });
      let arr = this.calculateTArr(specList).flat();
      let i = 0;
      this.tableList.forEach((item) => {
        item.variantSpecs.forEach((item2, index2) => {
          Object.defineProperty(item2, 'specName', {
            configurable: true,
            enumerable: true,
            get() {
              return _this.specList[index2].specName;
            },
          });
          Object.defineProperty(item2, 'specUnit', {
            configurable: true,
            enumerable: true,
            get() {
              return _this.specList[index2].specUnit;
            },
          });

          {
            (function () {
              let tempI = i++;
              Object.defineProperty(item2, 'specVal', {
                configurable: true,
                enumerable: true,
                get() {
                  return specList[index2][arr[tempI]].specVal;
                },
              });
            })();
          }
        });
        Object.defineProperty(item, 'sku', {
          enumerable: true,
          configurable: true,
          get() {
            return item.variantSpecs.reduce((a, b) => (a ? a + ':' + b.specVal : b.specVal), '');
          },
        });
      });
    },
    // 计算二维数组所有的排列，这里只需要索引
    calculateTArr(arr, j = 0, value = [], backArr = []) {
      if (arr.length == 0) return backArr;
      for (let index = 0; index < arr[j].length; index++) {
        let temp = [...value];
        temp.push(index);
        if (j == arr.length - 1) {
          backArr.push(temp);
          continue;
        } else {
          this.calculateTArr(arr, j + 1, temp, backArr);
        }
      }
      return backArr;
    },
    // 判断是否不显示保存
    judgeShowSave(obj) {
      // 只要修改了规格那么就只能同步保存经营产品
      const { tableList } = this;
      const skuList = obj.map((item) => item.map((item2) => item2.specVal).join(':'));

      const skuList2 = tableList.map((item) => item.variantSpecs.map((item2) => item2.specVal).join(':'));
      const flag = skuList.length != skuList2.length;
      if ((!flag && skuList.every((item) => skuList2.includes(item))) || flag) {
        // 只要规格改变了就触发
        this.$emit('showSave', false);
      }
    },
    // 是否重新获取规格列表
    judgeResetTable(flag) {
      if (flag) return true;
      let length1 = this.tableList.length;
      let length2 = 0;
      let tempArr = this.specList.map((item) => {
        return item.specValList.filter((item) => item.specVal).length;
      });
      if (tempArr.length == 1) {
        length2 = tempArr[0];
      } else if (tempArr.length > 1) {
        length2 = tempArr.reduce((a, b) => a * b, 1);
      }
      if (this.tableList.length && this.tableList[0].variantSpecs && this.tableList[0].variantSpecs.length != this.specList.length) {
        // 表格中的规格列的个数与规格的个数不一样要重置表格
        return true;
      }
      if (length1 == length2) {
        return false;
      }
      return true;
    },
    // 设置默认值
    handleSetDefault(row) {
      this.tableList.forEach((item) => {
        item.defaultFlag = 0;
      });
      row.defaultFlag = 1;
    },
    // 校验数据
    checkSpec() {
      let tableList = this.tableList;
      let specList = this.specList.map((item) => item.specName);
      if (Array.isArray(new Set(specList)).length < this.specList.length) {
        this.$message.error('规格名重复');
        return;
      }

      if (!this.serverType == 3 && !tableList.length) {
        return true;
      }

      let flag = false;

      if (this.serverType == 3 && !tableList.length) {
        this.$message.error('租赁产品必须是多规格的');
        return;
      }

      flag = tableList.find((item, index) => {
        if (!item.variantSpecs.some((item) => item.specVal)) {
          this.$message.error('请补充规格值');
          return true;
        }

        if (!item.variantSpecs.some((item) => item.specName)) {
          this.$message.error('请补充规格名');
          return true;
        }

        if (this.serverType == 3) {
          if (item.rentTime == '0') {
            this.$message.error('时长不可以为0');
            return true;
          }
          if (!item.rentTime && !item.rentFlag) {
            this.$message.error('不计时一定要填写时长');
            return true;
          }

          if (!item.rentFlag && !item.renewPrice && item.renewPrice !== 0) {
            this.$message.error('不计时一定要填写续费价格');
            return true;
          }

          if (!item.rentFlag && !item.renewTime && item.renewTime !== 0) {
            this.$message.error('不计时一定要填写续费时长');
            return true;
          }

          if (item.deposit == '0') {
            this.$message.error('押金不能为0');
            return true;
          }
          if (!item.deposit) {
            this.$message.error('请补充押金');
            return true;
          }
        }

        if (this.serverType == 4) {
          if (!item.waiters.length) {
            this.$message.error('请选择服务员');
            return true;
          }
          if (item.relationWaiters.some((item2) => !item2.prepareTime || !item2.serviceTime)) {
            this.$message.error(`请补充完整第${index + 1}行服务员工作时间`);
            return true;
          }
        }

        if (!item.price && parseInt(item.price) !== 0) {
          this.$message.error('请补充价格');
          return true;
        }

        if (!item.price && parseInt(item.salePrice) !== 0) {
          this.$message.error('请补充售价');
          return true;
        }

        if (!item.costPrice && parseInt(item.costPrice) !== 0) {
          this.$message.error('请补充成本价');
          return true;
        }
        if (!item.stock && parseInt(item.stock) !== 0 && this.showStock) {
          this.$message.error('请把库存补完整');
          return true;
        }
      });
      if (flag) return;

      flag = this.specList.find((item) => {
        const val = item.specValList.find((item2, index) => {
          return item.specValList.findIndex((item3) => item3.specVal == item2.specVal) != index;
        });
        if (val) {
          this.$message.error('规格名为' + item.specName + '的规格值' + val.specVal + '重复');
          return true;
        }
      });

      if (flag) return;

      if (tableList.length > 0) {
        this.info.stock = tableList.reduce((a, b) => Number(a) + Number(b.stock), 0);

        if (!tableList.some((item) => item.defaultFlag)) {
          this.$message.error('请设置默认值');
          return;
        }
      }
      return true;
    },
    combine(tempArr, arr, value, index) {
      if (index >= arr.length) {
        tempArr.push(value);
        return;
      }
      for (let i = 0; i < arr[index].length; i++) {
        let temp = JSON.parse(JSON.stringify(value));
        temp.push(arr[index][i]);
        this.combine(tempArr, arr, temp, index + 1);
      }
    },
    calculateCombine(arr) {
      if (arr.length == 0) return [];
      let tempArr = [];
      this.combine(tempArr, arr, [], 0);
      return tempArr;
    },
    // 比较新生成的规格表格与旧的
    compareSpec(tempArr, tableList) {
      let temp1 = tempArr.map((item) => {
        return item.variantSpecs.map((item2) => (item2.specVal ? item2.specVal : '')).join(':');
      });

      let temp2 = tableList.map((item) => {
        return item.variantSpecs.map((item2) => (item2.specVal ? item2.specVal : '')).join(':');
      });
      temp1.forEach((item, index) => {
        let indx = temp2.findIndex((item3) => {
          const arr1 = item.split(':');
          const arr2 = item3.split(':');
          return arr1.every((item4) => arr2.includes(item4)) && arr1.length == arr2.length;
        });

        if (indx != -1) {
          tempArr[index] = JSON.parse(JSON.stringify(tableList[indx]));
        }
      });
      // 清空数组，但是不改变地址
      this.tableList.length = 0;
      // 这里不能使用Array.prototype否则的话数据不是响应式的
      this.tableList.push.apply(this.tableList, tempArr);
    },
    checkWaiterTime(row, index) {
      const { showWaiterTime } = this;
      // this.rowIndex = index
      // this.rowItem = row
      showWaiterTime.show = true;
      showWaiterTime.relationWaiters = row.relationWaiters;
      // JSON.parse(JSON.stringify(row.relationWaiters))
      showWaiterTime.waiters = row.waiters;
    },
    inputVerify(i,row) {
      switch (i) {
        case 1: // 这里改为数字1
          if (!/^\d+(\.\d{1})?$/.test(row.discountOld)) { // 使用逻辑或
            row.discountOld = 0; // 设置默认值
            this.$message.error("最多只能有1位小数");
          }
          break;
        case 3: // 这里改为数字2
          if (!/^\d+(\.\d{1})?$/.test(row.discountPmc)) { // 使用逻辑或
            row.discountPmc = 0; // 设置默认值
            this.$message.error("最多只能有1位小数");
          }
          break;
        case 2: // 这里改为数字1
          if (!/^\d+(\.\d{1})?$/.test(row.rebateOld)) { // 使用逻辑或
            row.rebateOld = 0; // 设置默认值
            this.$message.error("最多只能有1位小数");
          }
          break;
        case 4: // 这里改为数字1
          if (!/^\d+(\.\d{1})?$/.test(row.rebatePmc)) { // 使用逻辑或
            row.rebatePmc = 0; // 设置默认值
            this.$message.error("最多只能有1位小数");
          }
          break;
      }
    }
    // 确认选择服务员工作时段
  },
};
</script>

<style lang="scss" scoped>
.el-collapse {
  border: 1px solid #e6e6e6;
  margin: 0 15px 20px 0;

  &::v-deep .el-collapse-item__header {
    justify-content: center;
    background-color: #f7f7f7;
    border-top: 1px solid #e6e6e6;
    border-bottom: 1px solid #e6e6e6;
    height: 38px;
    line-height: 38px;

    .el-collapse-item__arrow {
      margin: 0;
    }
  }

  .el-collapse-item {
    &::v-deep .el-collapse-item__wrap {
      border: none;

      .el-collapse-item__content {
        padding-bottom: 0;
      }
    }

    .box {
      width: 96%;
      margin: 30px auto;
      box-sizing: border-box;
      border: 1px solid #ebe7e7;
      padding: 10px;
      position: relative;

      &:hover {
        box-shadow: 0 0 3px rgba($color: #000000, $alpha: 0.2);
      }

      .delete-spec {
        position: absolute;
        right: 33px;
        z-index: 1;
      }

      .el-row {
        display: flex;
        flex-wrap: wrap;

        .item {
          display: flex;
          align-items: center;
          margin: 14px 20px 14px 0;
          flex-shrink: 0;
          position: relative;
          margin-right: 80px;

          .label {
            margin: 0 8px;
            width: 60px;
            text-align: end;
          }

          .value {
            width: 220px;

            .el-select {
              width: 100%;
            }
          }

          .el-button {
            margin-left: 4px;
            position: absolute;
            right: -60px;
            top: 2px;
          }
        }
      }

      .bottom {
        margin: 10px auto;
        text-align: center;
      }
    }

    .el-table {
      padding-top: 20px;
      overflow: auto;

      .copy {
        padding: 2px 4px;
      }
    }

    .operate {
      padding: 20px 0;
      text-align: center;
    }
  }

  .upload-img {
    &::v-deep .el-upload {
      width: auto;

      .el-upload-dragger {
        width: 100px !important;
        height: 100px !important;
      }
    }

    .el-icon-plus {
      font-size: 24px;
      vertical-align: -24px;
    }
  }

  .more-img__container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;

    .more-img {
      position: relative;

      width: 100px;
      margin-bottom: 5px;

      .el-image {
        width: 100px !important;
        height: 100px !important;
      }

      .el-icon-close {
        position: absolute;
        right: 0;
        top: 0;
      }
    }

    .more-img__upload {
      width: fit-content;
      margin-bottom: 5px;

      &::v-deep .upload-oss {
        width: fit-content;
      }
    }
  }

  .readonly {
    ::v-deep .el-input__inner {
      color: #606266;
      background-color: white;
    }
  }
}
</style>
